package com.pay.common.aop;

import com.pay.common.exception.BusinessException;
import com.pay.common.util.ExceptionHelpUtil;
import com.pay.common.util.GsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * http请求和响应
 * Created by yinhuachang on 2018/5/30.
 */
@Aspect
@Component
public class LogAopAction {
    final Logger logger = LoggerFactory.getLogger(LogAopAction.class);
    @Autowired
    ExceptionHelpUtil exceptionHelpUtil;

    @Pointcut("execution(public * com.pay.controller..*(..))")
    private void pointCutMethod(){}

    @Before("pointCutMethod()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String contentType=request.getContentType();
        logger.info("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        logger.info("Class{" + joinPoint.getSignature().getDeclaringTypeName() + "."+ joinPoint.getSignature().getName()+"}");
        logger.info("Request{Url="+url+"}");
        logger.info("Request{ContentType="+contentType+"，Mehtod="+method+"}");
    }

    @AfterReturning(returning = "ret", pointcut = "pointCutMethod()")// returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("Response" + GsonUtils.toJson(ret));
    }

    // 对异常处理
    @AfterThrowing(value = "pointCutMethod()",throwing = "e")
    public void doThrowing(Throwable e){
        logger.info("系统未知异常捕获抛出："+e);
//        exceptionHelpUtil.saveException("LogAopAction:doThrowing:58",new BusinessException("系统未知异常捕获抛出："+e),"系统未知异常捕获抛出");
    }

}
